﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DataAccess.Sys.BO;
using AMS.DataAccess.Sys.Interfaces;

public partial class User_AddUser : BaseWorkPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!ParseArguments())
        {
            return;
        }

        if (!IsPostBack)
        {
            if (action == "edit")
            {
                DoDataBind();
            }
        }
    }

    bool ParseArguments()
    {
        if (!IsPostBack)
        {
            string msg = Request.QueryString["msg"];
            MsgInfo(msg);
        }

        action = Request.QueryString["op"];
        if (string.IsNullOrEmpty(action))
        {
            action = "add";
        }
        else
        {
            // edit
            if (!ParseIntParameter("id", true, out itemId))
            {
                GlobalTransfer.RedirectToErrorPage("参数不正确");
                return false;
            }
        }

        return true;
    }

    private void DoDataBind()
    {
        IUserManager userMgr = ManagerFactory.CreateUserManager();
        UserInfo user = userMgr.GetUser(CallContext, itemId);
        if (user != null)
        {
            if (user.isSysUser || user.isReadOnly)
            {
                ucUser.ShowUser(user);
                btnSave.Enabled = false;
                MsgError("用户信息只读哎呀");
            }
            else
            {
                ucUser.ShowUser(user);
            }

            lblTitle.Text = "编辑用户 - " + user.Name;
        }
        else
        {
            MsgInfo("用户不存在，请刷新列表后重试");
        }
    }

    int itemId;
    string action = "add";

    protected void btnSave_Click(object sender, EventArgs e)
    {
        UserInfo user;
        IUserManager userMgr = ManagerFactory.CreateUserManager();
        if (action == "add")
        {
            user = new UserInfo();
        }
        else
        {
            user = userMgr.GetUser(CallContext, itemId);
            if (user == null)
            {
                MsgInfo("用户不存在");
                return;
            }
        }

        if (ucUser.GetUserInfo(user))
        {
            // TODO: fill other fields
            if (action == "add")
            {
                //user.CreateUserID = CallContext.UserID;
                userMgr.AddUser(CallContext, user);
                string url = "AddUser.aspx?op=edit&id=" + user.AID.ToString() + "&msg=添加用户成功";
                Server.Transfer(url);
            }
            else
            {
                userMgr.UpdateUser(CallContext, user);
                MsgInfo("更新用户成功");
            }
        }
        else
        {
            MsgError("信息输入不完整");
        }
    }
}
